package tr.edu.yildiz.ce.dap.apm.commands;

import java.util.List;

import tr.edu.yildiz.ce.dap.apm.commands.basic.BasicReply;
import tr.edu.yildiz.ce.dap.apm.util.AppCache;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandConstants;
import tr.edu.yildiz.ce.dap.appagent.model.App;
import tr.edu.yildiz.ce.dap.appagent.model.AppDefinition;
import tr.edu.yildiz.ce.dap.appagent.model.AppList;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;

public class RegisterCommandReply extends BasicReply{

	@Override
	public DapMessage reply(DapMessage input) {
		DapMessage output = new DapMessage();
		output.setCommand(CommandConstants.REGISTER);
		output.setAgentName(input.getAgentName());
		output.setRegistrationId(appService.register(input.getAgentName(), input.getAgentListeningPort().intValue()));
		output.setResponse(CommandConstants.RESPONSE.OK);
		addAutoDeployApplications(output);
		return output;
	}

	private void addAutoDeployApplications(DapMessage output){
		AppList appList = new AppList();
		List<AppDefinition> list =  AppCache.getInstance().getAutoAppDefList();
		for (AppDefinition appDefinition : list) {
			App app = new App();
			app.setName(appDefinition.getApp().getName());
			app.setVersion(appDefinition.getApp().getVersion());
			appList.getApp().add(app);
		}
		output.setAppList(appList);
	}

	
}
